package model

import (
	"../utils"
	//"encoding/json"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/pborman/uuid"
	"strings"
	"time"
)

const DEFAULT_FIELD_STR  string = "id,avatar,email,nickname,address,phone,name,age,sex,created_at"

type User struct {
	ID               uint64  `json:"id" gorm:"primary_key"`
	Avatar           string  `json:"avatar"`
	Email            string  `json:"email" gorm:"not null;unique"`
	Name             string  `json:"name"`
	//Username         string  `json:"username" gorm:"not null;"`
	Nickname         string  `json:"nickname"`
	Age              uint64  `json:"age"`
	Sex              string  `json:"sex"`
	Address          string `json:"address"`
	Phone            string  `json:"phone"`
	Groups           []Group `gorm:"many2many:user_groups;"`
	Tags             []Tag   `gorm:"many2many:user_tags;"`
	Password         string  `json:"password" gorm:"not null"`
	Password_Confirm string  `json:"password_confirm"`
	Salt             string  `json:"salt"`
	CreatedAt        time.Time `json:"createtime"`
	UpdatedAt        time.Time
}


func (u User) Get() (result User){
	mydb.Select("id," + DEFAULT_FIELD_STR ).First(&result, u.ID)

	return result
}

func (u User) GetAll(fields []string,page, pageSize uint64,filter_by string ,filter_id uint64) ( users []User, total uint64 ) {
	users = []User{}
	var fields_str string
	var has_id_field bool
	var offset = (page - 1) * pageSize

	if len(fields) > 0 {
		for _, value := range fields {
			if value == "ID" {
				has_id_field = true
			} else {
				has_id_field = false
			}
		}
		if has_id_field {
			fields_str = strings.Join(fields, ",")
		} else {
			fields_str = "ID," + strings.Join(fields, ",") //没有ID的情况下需要自动加上ID字段
		}
	} else {
		fields_str = DEFAULT_FIELD_STR //默认情况下请求的字段
	}

	if strings.EqualFold(filter_by,"group") {
		mydb.Select(fields_str).Joins("right join user_groups on users.id=user_groups.user_id and user_groups.group_id = ?", filter_id).Offset(offset).Limit(pageSize).Find(&users)
	}else if strings.EqualFold(filter_by,"tag"){
		mydb.Select(fields_str).Joins("right join user_tags on users.id=user_tags.user_id and user_tags.tag_id = ?", filter_id).Offset(offset).Limit(pageSize).Find(&users)
	}else {
		mydb.Select(fields_str).Offset(offset).Limit(pageSize).Find(&users)
		mydb.Model(u).Count(&total)
	}

	return users,total
}

func (u User) Save() ( User ,  error) {
	tx := mydb.Begin()
	u.Salt = strings.Replace(uuid.NewUUID().String(), "-", "", -1)
	u.Password = utils.EncryptPassword(u.Password, u.Salt)

	if u.ID > 0 {
		tx.Save(&u)
	}else {
		if err := tx.Create(&u).Error; err != nil {
			tx.Rollback()
			return u,err
		}
	}

	tx.Commit()

	return u ,nil
}

func (u User) Remove(ids []uint64) (err error) {
	tx := mydb.Begin()
	if err = tx.Exec("DELETE FROM users  WHERE id IN (?) ", ids ).Error ; err != nil {
		tx.Rollback()
		return  err
	}

	if err = tx.Exec("DELETE FROM user_groups  WHERE user_id IN (?) ", ids ).Error ; err != nil {
		tx.Rollback()
		return  err
	}
	if err = tx.Exec("DELETE FROM user_tags  WHERE user_id IN (?) ", ids ).Error ; err != nil {
		tx.Rollback()
		return  err
	}

	tx.Commit()
	return nil
}

func (u *User) Valid(email string, password string) bool {
	mydb.Where("email = ?", email).First(&u)
	if u.checkPassword(password) {
		return true
	}
	return false
}

// 检查密码是否正确
func (u User) checkPassword(password string) bool {
	return u.Password == utils.EncryptPassword(password, u.Salt)
}

//
//func (u *User) MarshalJSON() ([]byte, error) {
//	return json.Marshal(&User{
//		ID:       u.ID,
//		Email:    u.Email,
//		Username: u.Username,
//	})
//}
